<template>
  <button class="location-toggle" @click="handlePickerLocation" :class="{ scroll: isScroll }">
    <view class="iconfont icon-ic_location51" />
    <text class="address">{{ address }}</text>
    <view class="iconfont icon-ic_downarrow" />
  </button>
</template>

<script>
import { getGeocoder } from "@/api/store";

export default {
  name: 'LocationSelector',
  props: {
    isScroll: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      location: null,
      address: "定位中..."
    };
  },
  created() {
    this.getCurrentLocation();
  },
  methods: {
    async getCurrentLocation() {
      try {
        const [error, result] = await uni.getLocation();
        if (error) throw new Error(error.errMsg);
        const { latitude, longitude } = result;
        this.location = {
          latitude,
          longitude
        };
        this.$store.commit('SET_LOCATION', this.location);

        const geoCoderRes = await getGeocoder({
          lat: latitude,
          long: longitude
        });
        this.address = geoCoderRes.data.formatted_addresses.recommend;
      } catch (err) { 
        // console.error(err);
      }
    },
    async handlePickerLocation() {
      try {
        const [error, result] = await uni.chooseLocation();
        if (error) throw new Error(error.errMsg);
        const { name, latitude, longitude } = result;
        this.location = {
          latitude,
          longitude
        };
        this.address = name;
        this.$store.commit('SET_LOCATION', this.location);
      } catch (err) {
        console.error(err);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.location-toggle {
  display: flex;
  align-items: center;
  background-color: transparent;
  color: #fff;
  font-size: 14px;
  line-height: 1;
  margin-right: 19rpx;

  &.scroll {
    color: #333;
  }

  .address {
    margin-left: 6rpx;
    max-width: 6em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
